<template>
  <!-- 筛选弹框 -->
  <div class="filter_pop" v-if="isShowPop">
    <div class="pop_cont">
      <!-- 测评量表分类 -->
      <div v-if="type === 1">
        <div class="problem_tit">测评量表分类：</div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: currentTypeIndex === index }"
            v-for="(item, index) in activityType"
            :key="index"
            @click="chooseType(item, index)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <!-- 问题类型 -->
      <div v-if="[3, 4].includes(type)">
        <div class="problem_tit">问题类型：</div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: currentQuestionType === index }"
            v-for="(item, index) in questionType"
            :key="index"
            @click="chooseQuestionType(item, index)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <!-- 结果生成日期 -->
      <div>
        <div class="problem_tit">结果生成日期：</div>
        <div class="dis_flex">
          <div class="date_box dis_flex" @click="chooseTime('start')">
            <img
              src="@/assets/images/evaluate/calendar_icon.png"
              alt=""
              class="date_img"
            />
            <div class="date_time">{{ convertYearMonthDay(startDate) }}</div>
          </div>
          <div class="dividing_line">--</div>
          <div class="date_box dis_flex" @click="chooseTime('end')">
            <img
              src="@/assets/images/evaluate/calendar_icon.png"
              alt=""
              class="date_img"
            />
            <div class="date_time">{{ convertYearMonthDay(endDate) }}</div>
          </div>
        </div>
      </div>
      <!-- 答题用户身份 -->
      <div v-if="type === 1">
        <div class="problem_tit">答题用户身份：</div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: currentPersonIndex === index }"
            v-for="(item, index) in eventPoster"
            :key="index"
            @click="choosePerson(item, index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
      <!-- 预约前置任务 -->
      <div v-if="type === 4">
        <div class="problem_tit">预约前置任务：</div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: currentTask === index }"
            v-for="(item, index) in prerequisiteTask"
            :key="index"
            @click="chooseTask(item, index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
      <!-- 咨询/预约是否完结 -->
      <div v-if="[3, 4].includes(type)">
        <div class="problem_tit">
          {{ type === 3 ? "咨询是否完结" : "预约是否完结：" }}
        </div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: currentOver === index }"
            v-for="(item, index) in isOver"
            :key="index"
            @click="chooseOver(item, index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
      <!-- 我的完成情况 -->
      <div v-if="[2, 6].includes(type)">
        <div class="problem_tit">我的完成情况：</div>
        <div class="answer_box dis_flex">
          <div
            class="answer_txt"
            :class="{ active: statusIndex === index }"
            v-for="(item, index) in completionStatus"
            :key="index"
            @click="chooseStatus(item, index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
      <div class="dis_flex between">
        <div class="clear_btn footer_btn" @click="toClear">清空</div>
        <div class="confirm_btn footer_btn" @click="toConfirm">确定</div>
      </div>
    </div>
    <van-datetime-picker
      v-model="currentDate"
      v-if="isShowPicker"
      type="date"
      title="选择年月日"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onConfirm"
      @cancel="isShowPicker = false"
    />
  </div>
</template>

<script>
import { queryQuestionSelector } from "@/api/consultation/record";
import { queryScaleType } from "@/api/evaluation/index";

// 提取计算半年前日期的函数
const getSixMonthsAgo = () => {
  const currentDate = new Date();
  const sixMonthsAgo = new Date(currentDate);
  sixMonthsAgo.setMonth(currentDate.getMonth() - 6);
  return sixMonthsAgo;
};

export default {
  props: {
    isShowPop: {
      type: Boolean,
      default: false,
    },
    type: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      questionType: [], // type 为 3 时，问题类型
      typeId: null,
      isShowPicker: false,
      currentDate: null,
      startDate: null,
      endDate: null,
      currentTypeIndex: null,
      currentPersonIndex: null,
      currentOver: null,
      currentQuestionType: null,
      currentTask: null,
      statusIndex: null,
      activityType: [],
      questionId: null,
      isOver: ["未完结", "已完结"],
      prerequisiteTask: ["无任务", "有任务"],
      eventPoster: ["用户本人", "用户家长"],
      completionStatus: ["部分完成", "全部完成"],
      currentType: "start",
      minDate: null,
      maxDate: null,
    };
  },
  watch: {
    isShowPop(newVal) {
      if (newVal) {
        this.setDateRange();
      }
    },
  },
  created() {
    if (this.type === 1) {
      this.getScaleType();
    }
    if ([3, 4].includes(this.type)) {
      this.getQuestionSelector();
    }
  },
  methods: {
    // 提取设置日期范围的函数
    setDateRange() {
      const currentDate = new Date();
      this.minDate = getSixMonthsAgo();
      this.maxDate = currentDate;
    },

    async getQuestionSelector() {
      try {
        const res = await queryQuestionSelector();
        if (res.code === 200) {
          this.questionType = res.data;
        }
      } catch (error) {
        console.error("获取问题类型失败:", error);
      }
    },

    convertYearMonthDay(date) {
      if (!date || !(date instanceof Date)) return "请选择日期";
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    chooseTime(type) {
      this.currentType = type;
      this.isShowPicker = true;
      if (type === "start") {
        this.setDateRange();
      } else {
        this.minDate = this.startDate || getSixMonthsAgo();
      }
      this.currentDate =
        type === "start"
          ? this.startDate || new Date()
          : this.endDate || new Date();
    },

    onConfirm(value) {
      if (this.currentType === "start") {
        this.startDate = value;
        if (this.endDate && this.endDate < value) {
          this.endDate = value;
        }
      } else {
        this.endDate = value;
      }
      this.isShowPicker = false;
    },

    async getScaleType() {
      try {
        const res = await queryScaleType();
        if (res.code === 200) {
          this.activityType = res.data;
        }
      } catch (error) {
        console.error("获取量表类型失败:", error);
      }
    },
    chooseType(item, index) {
      this.currentTypeIndex = index;
      this.typeId = item.id;
    },
    choosePerson(item, index) {
      this.currentPersonIndex = index;
    },
    chooseStatus(item, index) {
      this.statusIndex = index;
    },
    chooseTask(item, index) {
      this.currentTask = index;
    },
    chooseQuestionType(item, index) {
      this.questionId = item.id;
      this.currentQuestionType = index;
    },
    chooseOver(item, index) {
      this.currentOver = index;
    },

    // 确定
    toConfirm() {
      let startDate = this.startDate ? new Date(this.startDate) : null;
      let endDate = this.endDate ? new Date(this.endDate) : null;
      if (startDate) {
        // 设置 startDate 为当天的 0 点
        startDate.setHours(0, 0, 0, 0);
      }
      if (endDate) {
        // 设置 endDate 为当天的 23:59:59
        endDate.setHours(23, 59, 59, 999);
      }

      const par = {
        start_time: startDate ? Math.floor(startDate.getTime() / 1000) : null,
        end_time: endDate ? Math.floor(endDate.getTime() / 1000) : null,
        answer_role:
          this.currentPersonIndex === null
            ? ""
            : this.currentPersonIndex === 0
            ? 1
            : 2,
        type_id: this.typeId,
        is_finish: this.statusIndex,
        is_end: this.currentOver,
        question_id: this.questionId,
        is_pre_task: this.currentTask,
      };
      this.$emit("closeFilterPop", par);
    },

    toClear() {
      const initialState = {
        currentTypeIndex: null,
        currentPersonIndex: null,
        startDate: null,
        endDate: null,
        currentDate: null,
        typeId: null,
        statusIndex: null,
        currentOver: null,
        currentQuestionType: null,
        currentTask: null,
        questionId: null,
      };
      Object.assign(this, initialState);
    },
  },
};
</script>

<style lang="less" scoped>
//弹框
::v-deep.van-popup--center {
  width: 100%;
}

::v-deep .van-picker {
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 2000;
  border-radius: 10px 10px 0 0;
  background: #f4f6fa;
  border: 1px solid #0aa7f4;
}

.dis_flex {
  display: flex;
  align-items: center;
}

.just-spa-between {
  justify-content: space-between;
}

.filter_pop {
  position: fixed;
  top: 200px;
  left: 0;
  width: 100%;
  height: calc(100% - 100px);
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.pop_cont {
  position: fixed;
  top: 110px;
  left: 50%;
  width: 100%;
  transform: translateX(-50%);
  background-color: white;
  padding: 20px;
  border-radius: 0px 0px 10px 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 1001;
}

.problem_tit {
  font-weight: bold;
  font-size: 14px;
  line-height: 14px;
  color: #000000;
  margin: 17px 0;
}

.date_box {
  width: 143.33px;
  height: 33.33px;
  line-height: 33.33px;
  background: linear-gradient(0deg, #ffffff 0%, rgba(255, 255, 255, 0) 100%),
    #ffffff;
  border: 0.33px solid #aaaaaa;
  border-radius: 6.67px;
  padding-left: 10px;
}

.date_img {
  width: 13.33px;
  height: 13.33px;
  margin-right: 10.67px;
}

.date_time {
  color: #555555;
  font-size: 14px;
  font-weight: bold;
}

.dividing_line {
  font-size: 14px;
  font-weight: bold;
  color: #000000;
  margin: 0 11px;
}

.answer_box {
  flex-wrap: wrap;
  margin: -6.67px -6.67px 0 0;
}

.answer_txt {
  width: 102px;
  height: 33.33px;
  line-height: 33.33px;
  text-align: center;
  background: #f4f6fa;
  border-radius: 6.67px;
  font-weight: bold;
  font-size: 14px;
  color: #555555;
  margin: 6.67px 6.67px 0 0;
}

.active {
  border: 0.33px solid #00aeff;
  color: #00aeff;
}

.footer_btn {
  width: 155px;
  height: 33.33px;
  line-height: 33.33px;
  text-align: center;
  font-size: 15.33px;
  font-weight: bold;
  border-radius: 6.67px;
  margin-top: 33.33px;
}

.clear_btn {
  border: 0.33px solid #dddddd;
  color: #333333;
}

.confirm_btn {
  color: #fff;
  background: linear-gradient(0deg, #ffffff -20%, rgba(255, 255, 255, 0) 20%),
    #0aa7f4;
}
</style>
